package cn.yunyichina.provider.base.service.impl;

import cn.yunyichina.provider.base.dao.DictionaryDao;
import cn.yunyichina.provider.base.dao.EventDao;
import cn.yunyichina.provider.base.dao.ModuleDao;
import cn.yunyichina.provider.base.dao.RemindSettingDao;
import cn.yunyichina.provider.base.entity.Dictionary;
import cn.yunyichina.provider.base.entity.Event;
import cn.yunyichina.provider.base.entity.Module;
import cn.yunyichina.provider.base.entity.RemindSetting;
import cn.yunyichina.provider.base.vo.RemindUserRequest;
import cn.yunyichina.provider.framework.annotation.validate.ValidateException;
import cn.yunyichina.provider.framework.annotation.validate.Validator;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by benny on 2017/5/15.
 */
@Service
public class RemindSettingServiceImpl {

    @Autowired
    private RemindSettingDao remindSettingDao;

    @Autowired
    private ModuleDao moduleDao;

    @Autowired
    private EventDao eventDao;

    static Logger logger = LoggerFactory.getLogger(RemindSettingServiceImpl.class);

    @Autowired
    private DictionaryDao dictionaryDao;

    /**
	 * 查找匹配的提醒人
	 * yyt.base.remindsetting.match
	 * @param strJson org_id,event_code
	 * @return
	 */
	public List<RemindSetting> matchRemindSetting(String strJson) {
		logger.info(strJson);
		RemindSetting remindSetting = JsonUtils.parseObject(strJson, RemindSetting.class);
		List<RemindSetting> list = remindSettingDao.matchRemindSetting(remindSetting.getOrgId(), remindSetting.getEventCode());
		return list;
	}

    /**
     * 提醒配置列表查询
     *
     * @param data
     * @return yyt.base.remind.setting.list
     */
    public Response listRemindSetting(String data) {

        logger.info("获取提醒配置数据入参>>listRemindSetting: " + data);
        Response response = new Response();
        Map<String, Object> result = new HashMap<>();

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String orgId = maps.get("org_id");
        String moduleCode = maps.get("module_code");
        String eventCode = maps.get("event_code");
        String remindUserName = maps.get("remind_user_name");
        String remindUserMobile = maps.get("remind_user_mobile");

        String page_num = maps.get("page_num");
        String page_size = maps.get("page_size");
        if (StringUtils.isBlank(page_num) || StringUtils.isBlank(page_size)) {
            response.setResultCodeAndMessage("1202", "page_num or page_size is empty");
            return response;
        }

        RemindSetting remindSetting = new RemindSetting();
        remindSetting.setModuleCode(moduleCode);
        remindSetting.setEventCode(eventCode);
        remindSetting.setOrgId(orgId);
        remindSetting.setRemindUserName(remindUserName);
        remindSetting.setRemindUserMobile(remindUserMobile);

        //查出总记录数
        long count = remindSettingDao.selectCount(remindSetting);
        logger.info("listRemindSetting is size:" + count);
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageNum(Integer.valueOf(page_num));
        pageInfo.setPageSize(Integer.valueOf(page_size));

        pageInfo.setTotal(count);
        pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
        List<String> orderColumns=new ArrayList<>();
        orderColumns.add("CREATED_TIME");
        List<RemindSetting> remindSettings = remindSettingDao.select(remindSetting,orderColumns,false, pageInfo);
        logger.info("get listRemindSetting data：" + JSON.toJSONString(remindSettings));
        result.put("list", remindSettings);
        result.put("page_info", pageInfo);
        response.setResult(JsonUtils.toJsonString(result));
        response.setResultCodeAndMessage("0", "查询成功!");
        return response;

    }

    /**
     * 删除提醒配置
     * @param data
     * @return
     * yyt.base.remind.setting.delete
     */
    public Response deleteRemindSetting(String data) {
        logger.info("删除提醒配置数据入参>>deleteRemindSetting: " + data);
        Response response = new Response();
        try {
            Map<String, Object> maps = JsonUtils.parseObject(data, Map.class);
            List<String> idList = JsonUtils.parseObject(maps.get("id"), List.class);
            logger.info("删除的idList:"+JSON.toJSONString(idList));
            remindSettingDao.deleteByIds(idList);
            response.setResultCodeAndMessage("0", "删除成功!");
            return response;
        } catch (Exception e) {
            logger.error("deleteRemindSetting,发生异常:" + e.getMessage(), e);
            response.setResultCodeAndMessage("1203", "deleteRemindSetting,发生异常:" + e.getMessage());
            e.printStackTrace();
            return response;
        }
    }

    /**
     * 获取提醒配置查询条件
     * yyt.base.remind.setting.Condition.get
     * @param data
     * @return
     */
    public Response getRemindSettingCondition(String data) {
        logger.info("获取提醒配置条件入参>>getRemindSettingConditon: " + data);
        Dictionary dictionary = JsonUtils.parseObject(data, Dictionary.class);
        Response response = new Response();
        List<String> selects = new ArrayList<>();
        selects.add("ID");
        dictionary.setParentId("0");
        if("EVENT".equalsIgnoreCase(dictionary.getDicCode())&&StringUtils.isBlank(dictionary.getCategoryCode())){
            response.setResultCodeAndMessage("1202", "category_code is empty");
        } else if ("MODULE".equalsIgnoreCase(dictionary.getDicCode())) {
            logger.info("获取提醒配置模块字典入参: " + JsonUtils.toJsonString(dictionary));
            List<Dictionary> dictionarys = dictionaryDao.select(dictionary, selects);
            logger.info("获取提醒配置模块字典返回结果: " + JsonUtils.toJsonString(dictionarys));
            if (dictionarys.size() > 0) {
                Dictionary dic = (Dictionary) dictionarys.get(0);
                dic.setParentId(dic.getId());
                dic.setId(null);
                logger.info("获取提醒配置模块字典所有模块请求: " + JsonUtils.toJsonString(dic));
                List<Dictionary> dictionaryList = dictionaryDao.select(dic);
                logger.info("获取提醒配置模块字典所有模块返回 getRemindSettingCondition: " + JsonUtils.toJsonString(dictionaryList));
                response.setResult(JsonUtils.toJsonString(dictionaryList));
            }
        } else if ("EVENT".equalsIgnoreCase(dictionary.getDicCode())) {
            String categoryCode=dictionary.getCategoryCode();
            dictionary.setCategoryCode(null);
            logger.info("获取提醒配置事件字典入参: " + JsonUtils.toJsonString(dictionary));
            List<Dictionary> dictionarys = dictionaryDao.select(dictionary, selects);
            logger.info("获取提醒配置事件字典返回结果: " + JsonUtils.toJsonString(dictionarys));
            if (dictionarys.size() > 0) {
                Dictionary dic = (Dictionary) dictionarys.get(0);
                dic.setParentId(dic.getId());
                dic.setCategoryCode(categoryCode);
                dic.setId(null);
                logger.info("获取提醒配置此模块所有事件请求: " + JsonUtils.toJsonString(dic));
                List<Dictionary> dictionaryList = dictionaryDao.select(dic);
                logger.info("获取提醒配置模块字典所有事件返回 getRemindSettingCondition: " + JsonUtils.toJsonString(dictionaryList));
                response.setResult(JsonUtils.toJsonString(dictionaryList));
            }
        } else {
            response.setResultCodeAndMessage("1202", "dic_code is not support");
        }
        return  response;
    }


    /**
     * 获取提醒配置module查询条件
     * yyt.base.remind.setting.Module.get
     * @param data
     * @return
     */
    public Response getRemindSettingModule(String data) {
        logger.info("获取模块入参>>getRemindSettingModule: " + data);
        Module module = JsonUtils.parseObject(data, Module.class);
        Response response = new Response();
        List<Module> moduleList=moduleDao.select(module);
        logger.info("获取模块返回结果: " + JsonUtils.toJsonString(moduleList));
        response.setResult(JsonUtils.toJsonString(moduleList));
        return  response;
    }

    /**
     * 获取提醒配置Event查询条件
     * yyt.base.remind.setting.Event.get
     * @param data
     * @return
     */
    public Response getRemindSettingEvent(String data) {
        logger.info("根据module获取事件入参>>getRemindSettingEvent: " + data);
        Event event = JsonUtils.parseObject(data, Event.class);
        Response response = new Response();
        if(event==null||cn.yunyichina.utils.commons.StringUtils.isEmpty(event.getModuleId())){
            response.setResultCodeAndMessage("1202", "module_id is empty");
            return  response;
        }
        List<Event> eventList=eventDao.select(event);
        logger.info("根据module获取事件返回结果: " + JsonUtils.toJsonString(eventList));
        response.setResult(JsonUtils.toJsonString(eventList));
        return  response;
    }


    /**
     * 批量保存提醒配置
     *yyt.base.remind.setting.save
     * @param data
     * @return
     */
    public Response saveRemindSetting(String data) {
        logger.info("保存提醒设置入参>>saveRemindSetting: " + data);
        RemindSetting remindSetting = JsonUtils.parseObject(data, RemindSetting.class);
        Response response = new Response();
        List<RemindSetting> remindSettingSaveList= new ArrayList<>();
        //检查参数合法性
        try {
            Validator.getInstance().validate(remindSetting);
        } catch (ValidateException ex) {
            logger.info(" 数据校验失败:" + ex.getMessage() + "|入参:" + data + "！");
            logger.error("error", ex);
            response.setResultCodeAndMessage("1206", "数据校验失败:" + ex.getMessage());
            return response;
        }
        Map<String, Object> maps = JsonUtils.parseObject(data, Map.class);
        List<RemindUserRequest> remindUserList = JsonUtils.parseArray(maps.get("user").toString(), RemindUserRequest.class);
        if (remindUserList==null||remindUserList.size()<1){
            response.setResultCodeAndMessage("1203","remindUser can not empty");
            return  response;
        }
        logger.info("提醒配置用户数据入参 remindUserList:"+JSON.toJSONString(remindUserList));
        if(remindUserList.size()>0){
            RemindSetting rs=new RemindSetting();
            BeanUtils.copyProperties(remindSetting, rs);
            StringBuilder sb=new StringBuilder();
            for (RemindUserRequest rr : remindUserList){
                RemindSetting rsave=new RemindSetting();
                BeanUtils.copyProperties(remindSetting, rsave);
                rsave.setId(PKGenerator.generateId());
                rsave.setRemindUserId(rr.getRemindUserId());
                rsave.setRemindUserName(rr.getRemindUserName());
                rsave.setRemindUserMobile(rr.getRemindUserMobile());
                rsave.setCreatedTime(DateUtils.dateToString(new Date()));
                rs.setRemindUserId(rr.getRemindUserId());
                List<RemindSetting> remindSettingList =remindSettingDao.select(rs);
                if(remindSettingList.size()>0){
                    RemindSetting tmp=remindSettingList.get(0);
                    sb.append("提醒人: ").append(tmp.getRemindUserName()).append(",电话: ").append(tmp.getRemindUserMobile()).append(";");
                }
                remindSettingSaveList.add(rsave);
            }
            if(sb.length()>0){
                logger.info("remindUser is Exist,details : "+sb.substring(0,sb.length()-1));
                response.setResultCodeAndMessage("1203","提醒用户存在 : "+sb.substring(0,sb.length()-1));
                return response;
            }
        }
        try{
            remindSettingDao.batchInsert(remindSettingSaveList);
            return response;
        }catch (Exception e) {
            logger.error("saveRemindSetting,保存发生异常:" + e.getMessage(), e);
            response.setResultCodeAndMessage("1203", "saveRemindSetting,发生异常:" + e.getMessage());
            e.printStackTrace();
            return response;
        }
    }

}
